<template>
    <textarea class="t-textarea" :class="[{ 'is-disabled': disabled }]" :value="currentValue" ref="textarea" :style="style" @input="handleInput" v-focus="focus"></textarea>
</template>

<script>
  import merge from './utils/merge';
  import calculateTextareaHeight from './utils/calculateTextareaHeight';

  export default {
    name: 'TTextarea',
    computed: {
      currentValue() {
        this.$nextTick(() => {
          this.modifyHeight();
        });
        return this.store.currentValue;
      },
      style() {
        return merge({}, this.store.boxStyle, {
          resize: this.resize,
        });
      },
    },
    data() {
      return {
        store: {
          currentValue: '',
          lastValue: '',
          boxStyle: '',
          setCurrentValue(payload) {
            this.lastValue = this.currentValue;
            this.currentValue = payload;
          },
          setBoxStyle(payload) {
            this.boxStyle = payload;
          },
        },
      };
    },
    props: {
      value: [String, Number],
      placeHolder: String,
      disabled: Boolean,
      focus: {
        type: Boolean,
        default: false,
      },
      resize: {
        type: String,
        default: 'none',
      },
      autosize: {
        type: Object,
        default: () => {
          return {
            minRows: '1',
            maxRows: '2',
          };
        },
      },
    },
    created() {
      this.store.setCurrentValue(this.value);
    },
    mounted() {
      this.modifyHeight();
    },
    watch: {
      value(val) {
        this.store.setCurrentValue(val);
      },
    },
    methods: {
      handleInput(event) {
        this.store.setCurrentValue(event.target.value);
        this.$emit('input', event.target.value);
      },
      modifyHeight() {
        const minRows = this.autosize.minRows;
        const maxRows = this.autosize.maxRows;
        this.store.setBoxStyle(calculateTextareaHeight(this.$refs.textarea, minRows, maxRows));
      },
    },
  };
</script>